using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebAPI.domain.Entity;
using WebAPI.domain.Repository;
using WebAPI.infrastructure.Db;

namespace WebAPI.api.Controllers
{
    [ApiController]
    [Route("[Controller]")]
    public class UserController : ControllerBase
    {
        private readonly IRepository<Users> _users;
        // private readonly SqlDbContext _db;

        public UserController(IRepository<Users> users)
        {
            // _db = db;
            _users = users;
        }
        public IEnumerable<Users> Index()
        {
            var users = _users.Table.ToArray();
            return users;
        }

        [HttpPost]
        public String CreateUser(Users entity)
        {
            // System.Console.WriteLine(entity);
            var user = new Users
            {
                UserName = entity.UserName,
                Password = entity.Password
            };
            // var list = _db.Users.Add(
            //     new Users
            //     {
            //         UserName = "张三",
            //         Password = "123456"
            //     });
            var list = _users.Add(user);
            // _db.SaveChanges();
            return "添加成功";
        }

        [HttpPut]
        [Route("{id}")]
        public Users update(Guid id, Users entity)
        {
            var user = _users.GetById(id);
            if (user != null)
            {
                user.UserName = entity.UserName;
                user.Password = entity.Password;
                _users.Update(user);
            }
            return user;
        }

        [HttpDelete]
        [Route("{id}")]
        public Users deleteUser(Guid id)
        {
            var user = _users.GetById(id);
            if (user != null)
            {
                user.IsDeleted = true;
                _users.Update(user);
            }
            return user;
        }
    }
}